<template>
    <!-- 查询表单区域 -->
    <el-form :model="CanShu" inline class="search-form" label-width="80px">
        <el-form-item label="盘点单号">
            <el-input v-model="CanShu.TrackingNumber" placeholder="请输入" />
        </el-form-item>

        <!-- 盘点类型下拉框 -->
        <el-form-item label="盘点类型">
            <el-select v-model="CanShu.TypeId" placeholder="请选择盘点类型" style="width: 160px; margin-right: 20px;">
                <el-option label="请选择" value="" />
                <el-option v-for="item in typeOptions" :key="item.typeId" :label="item.typeName" :value="item.typeId" />
            </el-select>
        </el-form-item>
        <!-- 盘点结果下拉框 -->
        <el-form-item label="盘点结果">
            <el-select v-model="CanShu.ResultId" placeholder="请选择盘点结果" style="width: 160px;">
                <el-option label="请选择" value="" />
                <el-option v-for="item in resultOptions" :key="item.resultId" :label="item.resultName"
                    :value="item.resultId" />
            </el-select>
        </el-form-item>
        <el-form-item label="仓库名称">
            <el-input v-model="CanShu.WarehouseName" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="GetStockingData">查询</el-button>
        </el-form-item>
        <el-form-item>
            <el-button type="success" @click="handleAdvancedSearch">高级搜索</el-button>
            <el-button type="info" @click="handleReset">重置</el-button>
        </el-form-item>
    </el-form>
    <!-- 操作按钮区域 -->
    <div class="inventory-container">
        <el-row class="operation-buttons">
            <el-button type="success" @click="handleCreate">新增</el-button>
            <el-button type="danger" @click="handleDelete">删除</el-button>
            <el-button type="warning" @click="handleExport" :loading="loading">
                导出数据
            </el-button>
            <el-button @click="handleInventory">作库</el-button>
            <el-button @click="handleLockWarehouse">锁定仓库</el-button>
            <el-button @click="handleRefresh">刷新</el-button>
        </el-row>

        <!-- 表格区域 -->
        <el-table :data="StockingData" border style="width: 100%" :loading="loading">
            <el-table-column prop="trackingNumber" label="盘点单号" align="center" />
            <el-table-column prop="resultName" label="结果名称" align="center" />
            <el-table-column prop="warehouseName" label="仓库名称" align="center" />
            <el-table-column prop="typeName" label="盘点类型" align="center" />
            <el-table-column prop="startTime" label="盘点开始时间" align="center">
                <template #default="scope">
                    {{formatDate(scope.row.startTime)}}
                </template>
            </el-table-column>
            <el-table-column prop="endTime" label="盘点结束时间" align="center">
                <template #default="scope">
                    {{formatDate(scope.row.endTime)}}
                </template>
            </el-table-column>
            <el-table-column prop="state" label="出库状态" align="center">
                <template #default="scope">
                    {{ scope.row.state === 1 ? '已出库' : '未出库' }}
                </template>
            </el-table-column>
            <el-table-column prop="inState" label="入库状态" align="center">
                <template #default="scope">
                    {{ scope.row.inState === 1 ? '已入库' : '未入库' }}
                </template>
            </el-table-column
            <el-table-column prop="inventoryName" label="盘点货品" align="center" />
            <el-table-column prop="inventorycount" label="盘点数量" align="center" />
            <el-table-column prop="inventorytota" label="盘盈数量" align="center" />
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button type="primary" text @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button type="danger" text @click="handleRemove(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <!-- 分页组件：首页、上一页、下一页、尾页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="Page.PageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="Page.PageSize"
            layout="total, prev, pager, next, jumper, ->, sizes" :total="Page.PageIndex" style="margin-top: 20px;">
            <!-- 自定义“首页”按钮 -->
            <template #prev>
                <el-button type="text" @click="goToFirstPage" :disabled="Page.PageIndex === 1">
                    首页
                </el-button>
            </template>

            <!-- 自定义“尾页”按钮 -->
            <template #next>
                <el-button type="text" @click="goToLastPage" :disabled="Page.PageIndex === Page.pageCount">
                    尾页
                </el-button>
            </template>
        </el-pagination>
    </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import router from '@/router'

// 查询参数（修正：初始值为 undefined，避免影响接口）
const CanShu = ref({
    TrackingNumber: '',
    ResultId: undefined, // 接口需 null/undefined 时用此
    WarehouseName: '',
    TypeId: undefined
})

// 下拉选项
const resultOptions = ref<any[]>([]) // 盘点结果
const typeOptions = ref<any[]>([])   // 盘点类型
const warehouseOptions = ref<any[]>([]) // 仓库（若需）

// 加载状态
const loading = ref(false)

// 列表数据和分页（修正：统一命名为 totalCount）
const StockingData = ref<any[]>([])
const Page = ref({
    PageIndex: 1,
    PageSize: 10,
    totalCount: 0,
    pageCount: 0
    // 修正：与接口返回字段统一
})

// 获取下拉选项（修正：接口地址与实际匹配）
const getTypeOptions = () => {
    axios.get("/reads/api/Inventory/GetType")
        .then(res => {
            typeOptions.value = res.data.data || []
        })
        .catch(err => {
            console.error("获取盘点类型失败：", err)
        })
}

const getResultOptions = () => {
    axios.get("/reads/api/Inventory/GetResult")
        .then(res => {
            resultOptions.value = res.data.data || []
        })
        .catch(err => {
            console.error("获取盘点结果失败：", err)
        })
}

// 日期格式化（安全处理）
const formatDate = (dateStr: string) => {
    if (!dateStr) return '-'
    const date = new Date(dateStr)
    return isNaN(date.getTime())
        ? dateStr.split(' ')[0]
        : `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

// 获取列表数据（修正：参数传递与接口匹配）
const GetStockingData = () => {
    loading.value = true
    axios.get("/reads/api/Inventory/GetInventory", {
        params: {
           PageIndex: Page.value.PageIndex,
            PageSize: Page.value.PageSize,
            TrackingNumber: CanShu.value.TrackingNumber,
            ResultId: CanShu.value.ResultId,
            WarehouseName: CanShu.value.WarehouseName,
            TypeId: CanShu.value.TypeId
        }
    })
        .then(res => {
            StockingData.value = res.data.pageData || []
            Page.value.totalCount = res.data.totaCount || 0
            Page.value.pageCount = res.data.pageCount || 0                             // 修正：与接口返回字段统一
        })
        .catch(err => {
            console.error("获取盘点数据失败：", err)
            ElMessage.error("加载数据失败，请重试")
        })
        .finally(() => {
            loading.value = false
        })
}

// 分页事件
const handleSizeChange = (size: number) => {
    Page.value.PageSize = size
    Page.value.PageIndex = 1
    GetStockingData()
}

const handleCurrentChange = (page: number) => {
    Page.value.PageIndex = page
    GetStockingData()
}

// 初始化：加载数据和下拉选项（修正：合并 onMounted）
onMounted(() => {
    GetStockingData()     // 加载列表
    getTypeOptions()      // 加载盘点类型
    getResultOptions()    // 加载盘点结果
    // getWarehouseOptions() // 若需仓库选项，取消注释
})

// 查询按钮（修正：重置分页并重新查询）
const handleSearch = () => {
    Page.value.PageIndex = 1
    GetStockingData()
}

// 重置表单
const handleReset = () => {
    CanShu.value = {
        TrackingNumber: '',
        ResultId: undefined,
        WarehouseName: '',
        TypeId: undefined
    }
    GetStockingData()
}


// 跳转首页
const goToFirstPage = () => {
  Page.value.PageIndex = 1
  // 调用 getData() 重新获取数据
}

// 跳转尾页
const goToLastPage = () => {
  Page.value.PageIndex = Page.value.PageIndex
  // 调用 getData() 重新获取数据
}

// 高级搜索（示例）
const handleAdvancedSearch = () => {
    ElMessage.info('高级搜索功能待实现')
}

// 操作按钮
const handleCreate = () => {
    router.push("/AddStorktaking")
}

const handleDelete = () => {
    ElMessage.info('删除功能待实现')
}

const handleExport = () => {
    ElMessage.info('导出功能待实现')
}

const handleInventory = () => {
    ElMessage.info('作库功能待实现')
}

const handleLockWarehouse = () => {
    ElMessage.info('锁定仓库功能待实现')
}

const handleRefresh = () => {
    GetStockingData()
}

const handleEdit = (row: any) => {
    ElMessage.info(`编辑：${JSON.stringify(row)}`)
}

const handleRemove = (row: any) => {
    ElMessage.info(`删除：${JSON.stringify(row)}`)
}
</script>

<style scoped>
.inventory-container {
    padding: 20px;
}

.search-form {
    margin-bottom: 16px;
}

.operation-buttons {
    margin-bottom: 16px;
}
</style>